const FavoriteName = require('./../models/favoriteNameModel');
const catchAsync = require('./../utils/catchAsync.js');
const AppError = require('./../utils/appError.js');
const factory = require('./handlerFactory');
const User = require('../models/userModel');
const Video = require('../models/videoModel');

// 查找当前用户的收藏夹
exports.findUserFavorites = async (req, res, next) => {
  // const user = req.user;
  const user = await User.findById(req.user.id).populate('favorite');
  // 返回用户的收藏夹数组
  res.status(200).json({
    results: user.favorite.length,
    status: 'success',
    favorites: user.favorite,
    message: 'The User FavroList',
  });
};

// 添加视频到用户的收藏夹中
exports.addVideoToFavorite = catchAsync(async (req, res, next) => {
  // 找到指定的收藏夹
  const { favoriteId, videoId, user } = req.body;
  const userU = await User.findById(user);
  const favorite = await FavoriteName.findById(favoriteId);

  if (!favorite) {
    return next(new AppError('Favorite not found', 404));
  }
  // 确保该用户是这个收藏夹的所有者
  // console.log('favorite.user=>' + favorite.user + '=>' + user);
  if (!favorite.user._id.equals(user)) {
    return next(
      new AppError('You are not authorized to add videos to this favorite', 404)
    );
  }
  console.log(favorite.videos);
  if (!favorite.videos || !Array.isArray(favorite.videos)) {
    favorite.videos = []; // 如果不存在或者不是数组，可以进行初始化
  }
  const video = await Video.findById(videoId);
  // console.log('video-->' + video);

  // 确保视频对象中存在 favoriteNames 字段，并且是一个数组
  if (!video.favoriteNames || !Array.isArray(video.favoriteNames)) {
    video.favoriteNames = []; // 如果不存在或者不是数组，可以进行初始化
  }
  if (!video.favoriteNames.includes(favoriteId)) {
    video.favoriteNames.push(favoriteId);
    await video.save();
  } else {
    return next(new AppError('cant not added twice', 404));
  }
  // 将视频添加到收藏夹中
  if (!favorite.videos.includes(videoId)) {
    favorite.videos.push(videoId);
    await favorite.save();
  } else {
    return next(new AppError('cant not added twice', 404));
  }

  res.status(200).json({
    status: 'success',
    message: 'Video added to favorite successfully',
  });
  // return { success: true, message: 'Video added to favorite successfully' };
});
exports.setUserUserId = (req, res, next) => {
  // Allow nested routes
  if (!req.body.user) req.body.user = req.params.userId;
  if (!req.body.user) req.body.user = req.user.id;
  next();
};

// 创建收藏夹的函数
exports.createFavorite = catchAsync(async (req, res, next) => {
  const { name, user } = req.body;
  const userU = await User.findById(user);
  // 创建收藏夹
  const favorite = await FavoriteName.create({
    name: name,
    user: user,
    videos: [], // 可选：初始化收藏夹中的视频为空数组
  });
  // 将收藏夹添加到当前用户的 favorites 列表中
  // 假设你的用户模型是 User，可以通过 userId 找到当前用户
  // await userU.save();
  res.status(200).json({
    status: 'success',
    favorite,
    message: 'Video added to favorite successfully',
  });
});
exports.getAllFavoriteNames = factory.getAll(FavoriteName);
exports.getFavoriteName = factory.getOne(FavoriteName);
exports.createFavoriteName = factory.createOne(FavoriteName);
exports.updateFavoriteName = factory.updateOne(FavoriteName);
exports.deleteFavoriteName = factory.deleteOne(FavoriteName);
